package top.jybill.utils;

import javax.sql.DataSource;
import java.sql.Connection;

public class ConnectionUtils {
  private ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
  private DataSource dataSource;

  public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
  }

  public ThreadLocal<Connection> getThreadLocal() {
    return threadLocal;
  }

  /**
   * 获取当前线程的Connection
   * @return
   */
  public Connection getThreadConnection() {
    Connection conn = threadLocal.get();

    try {
      // 没有Conn
      if (conn == null) {
        conn = dataSource.getConnection();
        conn.setAutoCommit(false);
        threadLocal.set(conn);
      }
    } catch (Exception e) {
      throw new RuntimeException("获取Connection失败");
    }
    return conn;
  }

  /**
   * 归还线程到线程池(javaWeb中tomcat会在初始化创建很多的线程放入线程池, 数据库连接池也会在一开始创建很多的链接放入连接池内)
   */
  /**
   * 释放资源
   */
  public void release() {
    try {
      threadLocal.remove();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
